package com.example.loginjwtdemo.interceptor;

import com.example.loginjwtdemo.util.JwtUserHolder;
import com.example.loginjwtdemo.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import sun.swing.StringUIClientPropertyKey;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ("/login".equalsIgnoreCase(request.getRequestURI())) {
            return true;
        }
        //进行验证
        String token = request.getHeader("Authorization");
        Claims claims = JwtUtil.parse(token);
        if (!StringUtils.isEmpty(claims)) {
            JwtUserHolder.add(claims.getSubject());
            //token不为空
            return true;
        }
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write("权限验证失败");
        writer.flush();
        writer.close();
        return false;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        JwtUserHolder.remove();
        super.afterCompletion(request, response, handler, ex);
    }
}
